﻿#include "admin_window.h"
#include "ui_adminwindow.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlTableModel>
#include <QMessageBox>
#include <QSqlError>
#include <QChart>
#include <QBarSeries>
#include <QBarSet>
#include <QValueAxis>
#include <QInputDialog>
#include <QDateEdit>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDebug>
#include <QStyledItemDelegate>
#include <QTimer>

using namespace QtCharts;

// 实现ApplicationDelegate类的方法
QString ApplicationDelegate::displayText(const QVariant &value, const QLocale &locale) const {
    if (currentColumn == 3) { // 身份类型列
        int identityType = value.toInt();
        switch (identityType) {
            case 2: return "商户";
            case 3: return "骑手";
            default: return value.toString();
        }
    } else if (currentColumn == 2) { // 审核状态列
        int status = value.toInt();
        switch (status) {
            case 0: return "待审核";
            case 1: return "已通过";
            case 2: return "已拒绝";
            default: return value.toString();
        }
    }
    return QStyledItemDelegate::displayText(value, locale);
}

void ApplicationDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    currentColumn = index.column();
    QStyledItemDelegate::paint(painter, option, index);
}

// 实现OrderStatusDelegate类的displayText方法
QString OrderStatusDelegate::displayText(const QVariant &value, const QLocale &locale) const {
    int status = value.toInt();
    switch (status) {
        case 1: return "下架";
        case 2: return "待审核";
        case 3: return "上架";
        case 4: return "待收餐";
        case 5: return "商家已接单";
        case 6: return "派送中";
        case 7: return "已送达";
        case 8: return "已完成";
        default: return value.toString();
    }
}

// 实现CustomCommodityModel类的data方法
QVariant CustomCommodityModel::data(const QModelIndex &index, int role) const {
    if (role == Qt::DisplayRole && index.column() == 5) { // 配送费列
        int business_id = QSqlTableModel::data(this->index(index.row(), 1), Qt::DisplayRole).toInt(); // 获取商户ID
        if (business_id > 0) {
            // 查询对应商户的配送费，使用正确的字段名business_id
            QSqlQuery query;
            query.prepare("SELECT delivery FROM business WHERE business_id = ?");
            query.addBindValue(business_id);
            if (query.exec() && query.next()) {
                return query.value(0);
            }
        }
        return QVariant("--"); // 如果没有找到对应的配送费，显示--
    }
    return QSqlTableModel::data(index, role);
}

AdminWindow::AdminWindow(QWidget *parent)
    : QWidget(parent), ui(new Ui::AdminWindow), useExternalDb(false) {
    ui->setupUi(this);
    setupUI();

    // 初始化数据库
    setupDatabase();

    // 初始化第一个选项卡
    onTabChanged(0);
}

AdminWindow::AdminWindow(database &extDb, QWidget *parent)
    : QWidget(parent), ui(new Ui::AdminWindow), useExternalDb(true) {
    ui->setupUi(this);
    setupUI();

    // 使用外部数据库连接
    db = extDb.getDb();

    // 初始化第一个选项卡
    onTabChanged(0);
}

void AdminWindow::setupUI() {
    // 设置窗口标题
    this->setWindowTitle("外卖平台管理系统");

    // 设置选项卡切换事件
    connect(ui->tabWidget, &QTabWidget::currentChanged,
            this, &AdminWindow::onTabChanged);

    // 设置Tab标题
    ui->tabWidget->setTabText(0, "用户管理");
    ui->tabWidget->setTabText(1, "骑手管理");
    ui->tabWidget->setTabText(2, "商户管理");
    ui->tabWidget->setTabText(3, "商品管理");
    ui->tabWidget->setTabText(4, "申请审批"); // 添加新的选项卡
#ifdef ENABLE_COMMENT_MANAGEMENT
    ui->tabWidget->setTabText(5, "评论管理");
    ui->tabWidget->setTabText(6, "订单记录");
    ui->tabWidget->setTabText(7, "营收统计");
#else
    ui->tabWidget->setTabText(5, "订单记录");
    ui->tabWidget->setTabText(6, "营收统计");
#endif

    // 连接用户管理按钮信号
    connect(ui->btnAddUser, &QPushButton::clicked, this, &AdminWindow::addUser);
    connect(ui->btnDeleteUser, &QPushButton::clicked, this, &AdminWindow::deleteUser);
    connect(ui->btnSaveUser, &QPushButton::clicked, this, &AdminWindow::saveUserChanges);

    // 连接骑手管理按钮信号
    connect(ui->btnAddRider, &QPushButton::clicked, this, &AdminWindow::addRider);
    connect(ui->btnDeleteRider, &QPushButton::clicked, this, &AdminWindow::deleteRider);
    connect(ui->btnSaveRider, &QPushButton::clicked, this, &AdminWindow::saveRiderChanges);

    // 连接商户管理按钮信号
    connect(ui->btnAddBusiness, &QPushButton::clicked, this, &AdminWindow::addBusiness);
    connect(ui->btnDeleteBusiness, &QPushButton::clicked, this, &AdminWindow::deleteBusiness);
    connect(ui->btnSaveBusiness, &QPushButton::clicked, this, &AdminWindow::saveBusinessChanges);

    // 连接商品管理按钮信号
    connect(ui->btnApprove, &QPushButton::clicked, this, &AdminWindow::changeCommodityStatus);
    connect(ui->btnReject, &QPushButton::clicked, this, &AdminWindow::deleteCommodity);

    // 修改商品管理按钮文本
    ui->btnApprove->setText("更改状态");
    ui->btnReject->setText("删除商品");

    // 添加商品管理的额外按钮
    QPushButton *btnAddCommodity = new QPushButton("添加商品", ui->commodityTab);
    QPushButton *btnSaveCommodity = new QPushButton("保存更改", ui->commodityTab);
    QPushButton *btnSearchCommodity = new QPushButton("搜索商品", ui->commodityTab);
    QPushButton *btnSortByPrice = new QPushButton("按价格排序", ui->commodityTab);
    QPushButton *btnSortBySales = new QPushButton("按销量排序", ui->commodityTab);

    // 将新按钮添加到布局中
    QHBoxLayout *commodityButtonLayout = nullptr;
    for (int i = 0; i < ui->commodityTab->layout()->count(); ++i) {
        QLayoutItem *item = ui->commodityTab->layout()->itemAt(i);
        if (QHBoxLayout *hbox = qobject_cast<QHBoxLayout*>(item->layout())) {
            commodityButtonLayout = hbox;
            break;
        }
    }

    if (commodityButtonLayout) {
        commodityButtonLayout->addWidget(btnAddCommodity);
        commodityButtonLayout->addWidget(btnSaveCommodity);
        commodityButtonLayout->addWidget(btnSearchCommodity);
        commodityButtonLayout->addWidget(btnSortByPrice);
        commodityButtonLayout->addWidget(btnSortBySales);

        // 连接新按钮信号
        connect(btnAddCommodity, &QPushButton::clicked, this, &AdminWindow::addCommodity);
        connect(btnSaveCommodity, &QPushButton::clicked, this, &AdminWindow::saveCommodityChanges);
        connect(btnSearchCommodity, &QPushButton::clicked, this, &AdminWindow::searchCommodity);
        connect(btnSortByPrice, &QPushButton::clicked, this, &AdminWindow::sortCommodityByPrice);
        connect(btnSortBySales, &QPushButton::clicked, this, &AdminWindow::sortCommodityBySales);
    }

    // 连接申请审批按钮信号
    connect(ui->btnApproveApplication, &QPushButton::clicked, this, &AdminWindow::approveApplication);
    connect(ui->btnRejectApplication, &QPushButton::clicked, this, &AdminWindow::rejectApplication);

    // 连接订单管理按钮信号
    connect(ui->btnDeleteOrder, &QPushButton::clicked, this, &AdminWindow::deleteOrder);
    connect(ui->btnSaveOrder, &QPushButton::clicked, this, &AdminWindow::saveOrderChanges);
    connect(ui->btnSearchOrder, &QPushButton::clicked, this, &AdminWindow::searchOrder);

#ifdef ENABLE_COMMENT_MANAGEMENT
    // 连接评论管理按钮信号
    connect(ui->btnAddComment, &QPushButton::clicked, this, &AdminWindow::addComment);
    connect(ui->btnDeleteComment, &QPushButton::clicked, this, &AdminWindow::deleteComment);
    connect(ui->btnSaveComment, &QPushButton::clicked, this, &AdminWindow::saveCommentChanges);
#endif

    // 连接刷新按钮 - 只在构造函数中连接一次，避免重复连接
    connect(ui->btnRefresh, &QPushButton::clicked, this, &AdminWindow::refreshRevenue);
}

AdminWindow::~AdminWindow() {
    // 检查未保存的更改
    checkUnsavedChanges();

    delete ui;

    // 只有在我们自己创建数据库连接时才关闭它
    if (!useExternalDb && db.isOpen()) {
        db.close();
    }
}

void AdminWindow::setupDatabase() {
    // 如果使用外部数据库连接，则跳过创建连接
    if (!useExternalDb) {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("Are_You_Hungry.db");

        if (!db.open()) {
            QMessageBox::critical(this, "数据库错误", db.lastError().text());
            return;
        }
    }

#ifdef ENABLE_COMMENT_MANAGEMENT
    // 创建评论表（如果不存在）
    QSqlQuery query;
    query.exec("CREATE TABLE IF NOT EXISTS comment ("
               "comment_id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "order_id INTEGER, "
               "user_id INTEGER, "
               "content TEXT, "
               "rating INTEGER, "
               "comment_time DATETIME, "
               "FOREIGN KEY (order_id) REFERENCES 'order'(oid), "
               "FOREIGN KEY (user_id) REFERENCES user(uid))");

    // 不再在这里连接评论管理按钮信号，因为已经在构造函数中连接过了
#endif
}

// 添加检查未保存更改的方法
void AdminWindow::checkUnsavedChanges() {
    if (commodityModel && commodityModel->isDirty()) {
        QMessageBox::StandardButton reply = QMessageBox::question(this, "未保存的更改",
            "您有未保存的商品更改，是否保存？",
            QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);

        if (reply == QMessageBox::Yes) {
            saveCommodityChanges();
        }
    }
}

void AdminWindow::onTabChanged(int index) {
    // 如果从商品管理选项卡切换到其他选项卡
    static int previousIndex = 0;
    if (previousIndex == 3 && index != 3) {
        checkUnsavedChanges();
    }
    previousIndex = index;

    switch(index) {
    case 0: initUserManagement(); break;
    case 1: initRiderManagement(); break;
    case 2: initBusinessManagement(); break;
    case 3: initCommodityManagement(); break;
    case 4: initApplicationReview(); break; // 添加申请审批选项卡初始化
#ifdef ENABLE_COMMENT_MANAGEMENT
    case 5: initCommentManagement(); break;
    case 6: initOrderHistory(); break;
    case 7: initRevenueAnalysis(); break;
#else
    case 5: initOrderHistory(); break;
    case 6: initRevenueAnalysis(); break;
#endif
    }
}

// 用户管理
void AdminWindow::initUserManagement() {
    userModel = new QSqlTableModel(this, db);
    userModel->setTable("user");
    userModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    userModel->select();

    // 设置表头
    userModel->setHeaderData(0, Qt::Horizontal, "用户id");
    userModel->setHeaderData(1, Qt::Horizontal, "用户昵称");
    userModel->setHeaderData(2, Qt::Horizontal, "用户的余额");
    userModel->setHeaderData(3, Qt::Horizontal, "电话的id");
    userModel->setHeaderData(4, Qt::Horizontal, "地址的id");

    ui->userTableView->setModel(userModel);
    ui->userTableView->resizeColumnsToContents();
}

// 添加用户
void AdminWindow::addUser() {
    int row = userModel->rowCount();
    userModel->insertRow(row);
    QMessageBox::information(this, "提示", "请在表格中编辑新用户信息，完成后点击保存按钮");
}

// 删除用户
void AdminWindow::deleteUser() {
    QModelIndex index = ui->userTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的用户");
        return;
    }

    int row = index.row();
    userModel->removeRow(row);
    QMessageBox::information(this, "提示", "用户已标记为删除，点击保存按钮确认删除");
}

// 保存用户更改
void AdminWindow::saveUserChanges() {
    if (userModel->submitAll()) {
        QMessageBox::information(this, "成功", "用户数据已保存");
    } else {
        QMessageBox::critical(this, "错误", "保存用户数据失败: " + userModel->lastError().text());
        userModel->revertAll();
    }
}

// 骑手管理
void AdminWindow::initRiderManagement() {
    riderModel = new QSqlTableModel(this, db);
    riderModel->setTable("rider");
    riderModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    riderModel->select();

    // 设置表头
    riderModel->setHeaderData(0, Qt::Horizontal, "骑手id");
    riderModel->setHeaderData(1, Qt::Horizontal, "骑手昵称");
    riderModel->setHeaderData(2, Qt::Horizontal, "电话id");
    riderModel->setHeaderData(3, Qt::Horizontal, "总收入");
    riderModel->setHeaderData(4, Qt::Horizontal, "状态");

    ui->riderTableView->setModel(riderModel);
    ui->riderTableView->resizeColumnsToContents();
}

// 添加骑手
void AdminWindow::addRider() {
    int row = riderModel->rowCount();
    riderModel->insertRow(row);
    QMessageBox::information(this, "提示", "请在表格中编辑新骑手信息，完成后点击保存按钮");
}

// 删除骑手
void AdminWindow::deleteRider() {
    QModelIndex index = ui->riderTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的骑手");
        return;
    }

    int row = index.row();
    riderModel->removeRow(row);
    QMessageBox::information(this, "提示", "骑手已标记为删除，点击保存按钮确认删除");
}

// 保存骑手更改
void AdminWindow::saveRiderChanges() {
    if (riderModel->submitAll()) {
        QMessageBox::information(this, "成功", "骑手数据已保存");
    } else {
        QMessageBox::critical(this, "错误", "保存骑手数据失败: " + riderModel->lastError().text());
        riderModel->revertAll();
    }
}

// 商户管理
void AdminWindow::initBusinessManagement() {
    businessModel = new QSqlTableModel(this, db);
    businessModel->setTable("business");
    businessModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    businessModel->select();

    // 设置表头
    businessModel->setHeaderData(0, Qt::Horizontal, "商户id");
    businessModel->setHeaderData(1, Qt::Horizontal, "商户名字");
    businessModel->setHeaderData(2, Qt::Horizontal, "手机的id");
    businessModel->setHeaderData(3, Qt::Horizontal, "地址的id");
    businessModel->setHeaderData(4, Qt::Horizontal, "配送费");
    businessModel->setHeaderData(5, Qt::Horizontal, "图片路径");
    businessModel->setHeaderData(6, Qt::Horizontal, "状态");
    businessModel->setHeaderData(7, Qt::Horizontal, "总收入");

    ui->businessTableView->setModel(businessModel);
    ui->businessTableView->resizeColumnsToContents();
}

// 添加商户
void AdminWindow::addBusiness() {
    int row = businessModel->rowCount();
    businessModel->insertRow(row);
    QMessageBox::information(this, "提示", "请在表格中编辑新商户信息，完成后点击保存按钮");
}

// 删除商户
void AdminWindow::deleteBusiness() {
    QModelIndex index = ui->businessTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的商户");
        return;
    }

    int row = index.row();
    businessModel->removeRow(row);
    QMessageBox::information(this, "提示", "商户已标记为删除，点击保存按钮确认删除");
}

// 保存商户更改
void AdminWindow::saveBusinessChanges() {
    if (businessModel->submitAll()) {
        QMessageBox::information(this, "成功", "商户数据已保存");
    } else {
        QMessageBox::critical(this, "错误", "保存商户数据失败: " + businessModel->lastError().text());
        businessModel->revertAll();
    }
}

// 商品管理
void AdminWindow::initCommodityManagement() {
    // 查询并输出commodity表的结构
    QSqlQuery tableInfoQuery;
    qDebug() << "查询commodity表结构:";
    if (tableInfoQuery.exec("PRAGMA table_info(commodity)")) {
        while (tableInfoQuery.next()) {
            QString columnName = tableInfoQuery.value(1).toString();
            QString columnType = tableInfoQuery.value(2).toString();
            qDebug() << "列名:" << columnName << "类型:" << columnType;
        }
    } else {
        qDebug() << "查询表结构失败:" << tableInfoQuery.lastError().text();
    }

    // 创建搜索框和过滤器控件
    QVBoxLayout *commodityLayout = qobject_cast<QVBoxLayout*>(ui->commodityTab->layout());
    if (!commodityLayout) return;

    // 删除旧的搜索框和过滤器（如果有的话）
    for (int i = commodityLayout->count() - 1; i >= 0; --i) {
        QLayoutItem *item = commodityLayout->itemAt(i);
        if (QHBoxLayout *hbox = qobject_cast<QHBoxLayout*>(item->layout())) {
            if (hbox->objectName() == "searchFilterLayout") {
                // 删除该布局中的所有控件
                while (hbox->count() > 0) {
                    QLayoutItem *subItem = hbox->takeAt(0);
                    if (subItem->widget()) delete subItem->widget();
                    delete subItem;
                }
                commodityLayout->removeItem(item);
                delete item;
                break;
            }
        }
    }

    // 创建搜索框和过滤器
    QHBoxLayout *searchFilterLayout = new QHBoxLayout();
    searchFilterLayout->setObjectName("searchFilterLayout");

    QLabel *searchLabel = new QLabel("搜索：", ui->commodityTab);
    QLineEdit *searchEdit = new QLineEdit(ui->commodityTab);
    searchEdit->setPlaceholderText("输入商品名称或ID");
    searchEdit->setObjectName("commoditySearchEdit");

    QLabel *filterLabel = new QLabel("状态过滤：", ui->commodityTab);
    QComboBox *statusFilter = new QComboBox(ui->commodityTab);
    statusFilter->setObjectName("statusFilterCombo");
    statusFilter->addItem("全部", -1);

    // 获取状态列表
    QSqlQuery statusQuery;
    if (statusQuery.exec("SELECT CSid, status FROM commodity_status")) {
        while (statusQuery.next()) {
            int statusId = statusQuery.value(0).toInt();
            QString statusName = statusQuery.value(1).toString();
            statusFilter->addItem(statusName, statusId);
        }
    } else {
        // 添加默认状态
        statusFilter->addItem("上架", 1);
        statusFilter->addItem("下架", 2);
        statusFilter->addItem("审核中", 3);
    }

    QPushButton *searchButton = new QPushButton("搜索", ui->commodityTab);
    QPushButton *resetButton = new QPushButton("重置", ui->commodityTab);

    // 添加到布局
    searchFilterLayout->addWidget(searchLabel);
    searchFilterLayout->addWidget(searchEdit, 2);  // 设置伸展因子为2
    searchFilterLayout->addWidget(filterLabel);
    searchFilterLayout->addWidget(statusFilter, 1);
    searchFilterLayout->addWidget(searchButton);
    searchFilterLayout->addWidget(resetButton);

    // 将布局添加到商品选项卡的顶部
    if (commodityLayout->count() > 0) {
        commodityLayout->insertLayout(0, searchFilterLayout);
    } else {
        commodityLayout->addLayout(searchFilterLayout);
    }

    // 连接信号槽
    connect(searchButton, &QPushButton::clicked, [this, searchEdit, statusFilter]() {
        QString searchText = searchEdit->text();
        int statusId = statusFilter->currentData().toInt();

        QStringList filters;
        if (!searchText.isEmpty()) {
            // 使用正确的字段名：com_name, com_id, business_id
            filters << QString("(com_name LIKE '%%1%' OR com_id LIKE '%%1%' OR business_id LIKE '%%1%')").arg(searchText);
        }

        if (statusId != -1) {
            // 使用正确的字段名：cs_id
            filters << QString("cs_id = %1").arg(statusId);
        }

        QString filterStr = filters.join(" AND ");
        qDebug() << "应用过滤条件:" << filterStr;
        commodityModel->setFilter(filterStr);
        commodityModel->select();
        qDebug() << "过滤后记录数:" << commodityModel->rowCount();

        if (commodityModel->rowCount() == 0 && !filterStr.isEmpty()) {
            QMessageBox::information(this, "搜索结果", "未找到匹配的商品");
        }
    });

    connect(resetButton, &QPushButton::clicked, [this, searchEdit, statusFilter]() {
        searchEdit->clear();
        statusFilter->setCurrentIndex(0);
        commodityModel->setFilter("");
        commodityModel->select();
    });

    // 初始化商品表格模型 - 使用自定义模型
    commodityModel = new CustomCommodityModel(this, db);
    commodityModel->setTable("commodity");
    commodityModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    commodityModel->select();

    // 设置表头 - 使用正确的字段名对应关系
    commodityModel->setHeaderData(0, Qt::Horizontal, "商品id");
    commodityModel->setHeaderData(1, Qt::Horizontal, "商户id");
    commodityModel->setHeaderData(2, Qt::Horizontal, "商品名称");
    commodityModel->setHeaderData(3, Qt::Horizontal, "价格");
    commodityModel->setHeaderData(4, Qt::Horizontal, "销售量");
    commodityModel->setHeaderData(5, Qt::Horizontal, "配送费");
    commodityModel->setHeaderData(6, Qt::Horizontal, "商品描述");
    commodityModel->setHeaderData(7, Qt::Horizontal, "状态id");

    ui->commodityTableView->setModel(commodityModel);
    ui->commodityTableView->resizeColumnsToContents();

    // 添加数据变更事件处理程序
    connect(ui->commodityTableView, &QTableView::clicked, [this](const QModelIndex &index) {
        // 如果用户点击了商户ID列
        if (index.column() == 1) {
            // 设置一个延迟检查，让用户有时间输入商户ID
            QTimer::singleShot(100, [this, index]() {
                int row = index.row();
                QVariant bidValue = commodityModel->data(commodityModel->index(row, 1)); // 商户ID

                // 如果商户ID有效
                if (bidValue.isValid() && !bidValue.isNull()) {
                    int business_id = bidValue.toInt();
                    if (business_id > 0) {
                        // 从business表获取配送费
                        QSqlQuery query;
                        query.prepare("SELECT delivery FROM business WHERE business_id = ?");
                        query.addBindValue(business_id);

                        if (query.exec() && query.next()) {
                            float delivery = query.value(0).toFloat();

                            // 通知用户
                            QMessageBox::information(this, "配送费更新",
                                QString("商户(ID: %1)的配送费已自动设置为: %2").arg(business_id).arg(delivery));
                        } else {
                            QMessageBox::warning(this, "警告",
                                QString("找不到商户ID %1 的配送费信息").arg(business_id));
                        }
                    }
                }
            });
        }
    });

    // 监听表格选择变化事件，动态启用/禁用按钮
    connect(ui->commodityTableView->selectionModel(), &QItemSelectionModel::selectionChanged,
        [this]() {
            bool hasSelection = ui->commodityTableView->selectionModel()->hasSelection();
            ui->btnApprove->setEnabled(hasSelection); // 更改状态按钮
            ui->btnReject->setEnabled(hasSelection);  // 删除商品按钮
        });

    // 初始时禁用按钮
    ui->btnApprove->setEnabled(false);
    ui->btnReject->setEnabled(false);
}

void AdminWindow::addCommodity() {
    int row = commodityModel->rowCount();
    commodityModel->insertRow(row);
    QMessageBox::information(this, "提示",
        "请在表格中编辑新商品信息，完成后必须点击\"保存更改\"按钮才能保存到数据库。");
}

void AdminWindow::deleteCommodity() {
    QModelIndex index = ui->commodityTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的商品");
        return;
    }

    int row = index.row();
    int com_id = commodityModel->data(commodityModel->index(row, 0)).toInt();

    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除",
                                                             "确定要删除选中的商品吗？",
                                                             QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        commodityModel->removeRow(row);

        if (commodityModel->submitAll()) {
            QMessageBox::information(this, "成功", "商品已删除");
            commodityModel->select(); // 刷新表格
        } else {
            QMessageBox::critical(this, "错误", "删除商品失败: " + commodityModel->lastError().text());
        }
    }
}

void AdminWindow::saveCommodityChanges() {
    // 不再需要为每一行设置配送费，因为配送费是从商户表中获取的，而不是商品表的字段

    // 保存更改
    if (commodityModel->submitAll()) {
        QMessageBox::information(this, "成功", "商品数据已保存");
    } else {
        QMessageBox::critical(this, "错误", "保存商品数据失败: " + commodityModel->lastError().text());
        commodityModel->revertAll();
    }
}

void AdminWindow::searchCommodity() {
    // 获取搜索控件
    QLineEdit *searchEdit = ui->commodityTab->findChild<QLineEdit*>("commoditySearchEdit");
    QComboBox *statusFilter = ui->commodityTab->findChild<QComboBox*>("statusFilterCombo");

    if (!searchEdit || !statusFilter) {
        // 如果找不到控件，使用对话框
        bool ok;
        QString searchText = QInputDialog::getText(this, "搜索商品",
                                                 "请输入商品名称或商户ID:",
                                                 QLineEdit::Normal,
                                                 "", &ok);
        if (ok && !searchText.isEmpty()) {
            // 使用正确的字段名
            QString filter = QString("com_name LIKE '%%1%' OR business_id LIKE '%%1%'").arg(searchText);
            qDebug() << "应用过滤条件:" << filter;
            commodityModel->setFilter(filter);
            commodityModel->select();
            qDebug() << "过滤后记录数:" << commodityModel->rowCount();

            if (commodityModel->rowCount() == 0) {
                QMessageBox::information(this, "搜索结果", "未找到匹配的商品");
                // 清除过滤器，显示所有数据
                commodityModel->setFilter("");
                commodityModel->select();
            }
        }
        return;
    }

    // 触发搜索按钮点击事件
    QString searchText = searchEdit->text();
    int statusId = statusFilter->currentData().toInt();

    QStringList filters;
    if (!searchText.isEmpty()) {
        // 使用正确的字段名
        filters << QString("(com_name LIKE '%%1%' OR com_id LIKE '%%1%' OR business_id LIKE '%%1%')").arg(searchText);
    }

    if (statusId != -1) {
        // 使用正确的字段名
        filters << QString("cs_id = %1").arg(statusId);
    }

    QString filterStr = filters.join(" AND ");
    qDebug() << "应用过滤条件:" << filterStr;
    commodityModel->setFilter(filterStr);
    commodityModel->select();
    qDebug() << "过滤后记录数:" << commodityModel->rowCount();

    if (commodityModel->rowCount() == 0 && !filterStr.isEmpty()) {
        QMessageBox::information(this, "搜索结果", "未找到匹配的商品");
    }
}

void AdminWindow::changeCommodityStatus() {
    QModelIndex index = ui->commodityTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要修改状态的商品");
        return;
    }

    int row = index.row();
    int com_id = commodityModel->data(commodityModel->index(row, 0)).toInt();
    int currentStatus = commodityModel->data(commodityModel->index(row, 7)).toInt();

    // 获取商品状态列表
    QSqlQuery statusQuery;
    QMap<int, QString> statusMap;
    QStringList statusList;

    statusQuery.exec("SELECT CSid, status FROM commodity_status");
    while (statusQuery.next()) {
        int statusId = statusQuery.value(0).toInt();
        QString statusName = statusQuery.value(1).toString();
        statusMap[statusId] = statusName;
        statusList << statusName;
    }

    // 如果没有状态数据
    if (statusList.isEmpty()) {
        statusList << "上架" << "下架" << "审核中";
    }

    // 让用户选择新状态
    bool ok;
    QString item = QInputDialog::getItem(this, "更改商品状态",
                                       "选择新状态:", statusList, 0, false, &ok);
    if (ok && !item.isEmpty()) {
        // 找到对应的状态ID
        int newStatusId = -1;
        for (auto it = statusMap.begin(); it != statusMap.end(); ++it) {
            if (it.value() == item) {
                newStatusId = it.key();
                break;
            }
        }

        // 如果找不到对应的状态ID，使用默认逻辑
        if (newStatusId == -1) {
            // 简单切换上架/下架状态
            if (item == "上架") {
                newStatusId = 1; // 假设上架的ID是1
            } else if (item == "下架") {
                newStatusId = 2; // 假设下架的ID是2
            } else {
                newStatusId = 3; // 假设审核中的ID是3
            }
        }

        // 更新商品状态，使用正确的字段名
        QSqlQuery updateQuery;
        updateQuery.prepare("UPDATE commodity SET cs_id = ? WHERE com_id = ?");
        updateQuery.addBindValue(newStatusId);
        updateQuery.addBindValue(com_id);

        if (updateQuery.exec()) {
            commodityModel->select(); // 刷新表格
            QMessageBox::information(this, "成功",
                "商品状态已临时更新。请点击\"保存更改\"按钮以永久保存修改。");
        } else {
            QMessageBox::critical(this, "错误", "更新商品状态失败: " + updateQuery.lastError().text());
        }
    }
}

void AdminWindow::sortCommodityByPrice() {
    // 使用正确的字段名
    commodityModel->setSort(3, Qt::AscendingOrder); // price是第4列（索引为3）
    commodityModel->select();
}

void AdminWindow::sortCommodityBySales() {
    // 使用正确的字段名
    commodityModel->setSort(4, Qt::DescendingOrder); // number是第5列（索引为4）
    commodityModel->select();
}

// 订单记录
void AdminWindow::initOrderHistory() {
    orderModel = new QSqlTableModel(this, db);
    orderModel->setTable("order_c");  // 修改为正确的表名
    orderModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    orderModel->select();

    // 设置表头
    orderModel->setHeaderData(0, Qt::Horizontal, "订单ID");
    orderModel->setHeaderData(1, Qt::Horizontal, "商品ID");
    orderModel->setHeaderData(2, Qt::Horizontal, "用户ID");
    orderModel->setHeaderData(3, Qt::Horizontal, "地址");
    orderModel->setHeaderData(4, Qt::Horizontal, "商家ID");
    orderModel->setHeaderData(5, Qt::Horizontal, "骑手ID");
    orderModel->setHeaderData(6, Qt::Horizontal, "联系电话");
    orderModel->setHeaderData(7, Qt::Horizontal, "下单时间");
    orderModel->setHeaderData(8, Qt::Horizontal, "订单状态");
    orderModel->setHeaderData(9, Qt::Horizontal, "完成时间");
    orderModel->setHeaderData(10, Qt::Horizontal, "数量");

    // 创建并设置订单状态委托
    OrderStatusDelegate *statusDelegate = new OrderStatusDelegate(this);
    ui->orderTableView->setItemDelegateForColumn(8, statusDelegate); // 订单状态是第9列（索引为8）

    ui->orderTableView->setModel(orderModel);
    ui->orderTableView->resizeColumnsToContents();
}

// 删除订单
void AdminWindow::deleteOrder() {
    QModelIndex index = ui->orderTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的订单");
        return;
    }

    int row = index.row();
    orderModel->removeRow(row);
    QMessageBox::information(this, "提示", "订单已标记为删除，点击保存按钮确认删除");
}

// 保存订单更改
void AdminWindow::saveOrderChanges() {
    if (orderModel->submitAll()) {
        QMessageBox::information(this, "成功", "订单数据已保存");
    } else {
        QMessageBox::critical(this, "错误", "保存订单数据失败: " + orderModel->lastError().text());
        orderModel->revertAll();
    }
}

// 搜索订单
void AdminWindow::searchOrder() {
    bool ok;
    QString searchText = QInputDialog::getText(this, "搜索订单",
                                             "请输入订单号:",
                                             QLineEdit::Normal,
                                             "", &ok);
    if (ok && !searchText.isEmpty()) {
        // 使用精确匹配而非模糊查询
        QString filter = QString("order_id = %1").arg(searchText);
        orderModel->setFilter(filter);
        orderModel->select();

        if (orderModel->rowCount() == 0) {
            QMessageBox::information(this, "搜索结果", "未找到匹配的订单");
            // 清除过滤器，显示所有数据
            orderModel->setFilter("");
            orderModel->select();
        }
    }
}

// 营收统计
void AdminWindow::initRevenueAnalysis() {
    // 设置UI
    setupRevenueUI();

    // 默认显示最近7天的数据
    QDate endDate = QDate::currentDate();
    QDate startDate = endDate.addDays(-7);

    startDateEdit->setDate(startDate);
    endDateEdit->setDate(endDate);

    // 更新所有图表和数据
    updateRevenueStats(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateRevenueChart(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateTransactionTable(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
}

void AdminWindow::setupRevenueUI() {
    // 清除chartContainer中的旧内容
    if (ui->chartContainer->layout()) {
        QLayoutItem *child;
        while ((child = ui->chartContainer->layout()->takeAt(0)) != nullptr) {
            if (child->widget()) {
                delete child->widget();
            }
            delete child;
        }
        delete ui->chartContainer->layout();
    }

    // 创建主垂直布局
    QVBoxLayout *mainLayout = new QVBoxLayout(ui->chartContainer);

    // 第一行: 过滤控件
    QHBoxLayout *filterLayout = new QHBoxLayout();

    // 时间范围快速选择
    QLabel *timeRangeLabel = new QLabel("时间范围:");
    timeRangeCombo = new QComboBox();
    timeRangeCombo->addItem("今日", 0);
    timeRangeCombo->addItem("昨日", 1);
    timeRangeCombo->addItem("本周", 2);
    timeRangeCombo->addItem("上周", 3);
    timeRangeCombo->addItem("本月", 4);
    timeRangeCombo->addItem("上月", 5);
    timeRangeCombo->addItem("自定义", 6);
    connect(timeRangeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AdminWindow::updateTimeRangeFilter);

    // 商家过滤器
    QLabel *businessLabel = new QLabel("商家筛选:");
    businessFilterCombo = new QComboBox();
    businessFilterCombo->addItem("全部商家", 0);

    // 查询所有商家并添加到下拉框
    QSqlQuery businessQuery(db);
    businessQuery.exec("SELECT business_id, name FROM business ORDER BY name");
    while (businessQuery.next()) {
        int businessId = businessQuery.value(0).toInt();
        QString businessName = businessQuery.value(1).toString();
        businessFilterCombo->addItem(businessName, businessId);
    }

    connect(businessFilterCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AdminWindow::updateBusinessFilter);

    // 日期选择器
    QLabel *startLabel = new QLabel("开始日期:");
    startDateEdit = new QDateEdit(QDate::currentDate().addDays(-7));
    startDateEdit->setCalendarPopup(true);

    QLabel *endLabel = new QLabel("结束日期:");
    endDateEdit = new QDateEdit(QDate::currentDate());
    endDateEdit->setCalendarPopup(true);

    queryButton = new QPushButton("查询");
    connect(queryButton, &QPushButton::clicked, this, &AdminWindow::customRevenueQuery);

    // 将过滤控件添加到布局
    filterLayout->addWidget(timeRangeLabel);
    filterLayout->addWidget(timeRangeCombo);
    filterLayout->addWidget(businessLabel);
    filterLayout->addWidget(businessFilterCombo);
    filterLayout->addWidget(startLabel);
    filterLayout->addWidget(startDateEdit);
    filterLayout->addWidget(endLabel);
    filterLayout->addWidget(endDateEdit);
    filterLayout->addWidget(queryButton);
    filterLayout->addWidget(ui->btnRefresh);

    // 第二行: 统计数据
    QHBoxLayout *statsLayout = new QHBoxLayout();

    // 创建显示关键统计数据的标签
    QFrame *statsFrame = new QFrame();
    statsFrame->setFrameShape(QFrame::StyledPanel);
    statsFrame->setStyleSheet("background-color: #f8f9fa; border-radius: 5px; padding: 10px;");
    QHBoxLayout *statsFrameLayout = new QHBoxLayout(statsFrame);

    // 总营收
    QVBoxLayout *totalRevenueLayout = new QVBoxLayout();
    QLabel *totalRevenueTitle = new QLabel("总营收");
    totalRevenueTitle->setStyleSheet("font-weight: bold;");
    totalRevenueLabel = new QLabel("¥0.00");
    totalRevenueLabel->setStyleSheet("font-size: 18px; color: #28a745;");
    totalRevenueLayout->addWidget(totalRevenueTitle);
    totalRevenueLayout->addWidget(totalRevenueLabel);

    // 订单数量
    QVBoxLayout *orderCountLayout = new QVBoxLayout();
    QLabel *orderCountTitle = new QLabel("订单数量");
    orderCountTitle->setStyleSheet("font-weight: bold;");
    orderCountLabel = new QLabel("0");
    orderCountLabel->setStyleSheet("font-size: 18px; color: #007bff;");
    orderCountLayout->addWidget(orderCountTitle);
    orderCountLayout->addWidget(orderCountLabel);

    // 平均订单金额
    QVBoxLayout *avgOrderLayout = new QVBoxLayout();
    QLabel *avgOrderTitle = new QLabel("平均订单金额");
    avgOrderTitle->setStyleSheet("font-weight: bold;");
    avgOrderLabel = new QLabel("¥0.00");
    avgOrderLabel->setStyleSheet("font-size: 18px; color: #fd7e14;");
    avgOrderLayout->addWidget(avgOrderTitle);
    avgOrderLayout->addWidget(avgOrderLabel);

    // 添加到统计框布局
    statsFrameLayout->addLayout(totalRevenueLayout);
    statsFrameLayout->addLayout(orderCountLayout);
    statsFrameLayout->addLayout(avgOrderLayout);

    // 添加统计框到统计布局
    statsLayout->addWidget(statsFrame);

    // 创建收入趋势图
    QHBoxLayout *chartsLayout = new QHBoxLayout();
    revenueChartView = new QChartView();
    revenueChartView->setRenderHint(QPainter::Antialiasing);
    revenueChartView->setMinimumHeight(250);
    chartsLayout->addWidget(revenueChartView);

    // 第五行: 交易明细表
    transactionTable = new QTableWidget();
    transactionTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    transactionTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    transactionTable->setAlternatingRowColors(true);
    transactionTable->setColumnCount(6);

    // 设置表头
    QStringList headers;
    headers << "订单ID" << "商家名称" << "订单金额" << "下单时间" << "状态" << "用户ID";
    transactionTable->setHorizontalHeaderLabels(headers);
    transactionTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 将所有布局添加到主布局
    mainLayout->addLayout(filterLayout);
    mainLayout->addLayout(statsLayout);
    mainLayout->addLayout(chartsLayout);
    mainLayout->addWidget(transactionTable);
}

void AdminWindow::updateTimeRangeFilter(int index) {
    QDate currentDate = QDate::currentDate();
    QDate startDate, endDate;

    // 禁用日期选择器，除非选择"自定义"
    bool enableDateEdits = (index == 6); // 6 是"自定义"选项的索引
    startDateEdit->setEnabled(enableDateEdits);
    endDateEdit->setEnabled(enableDateEdits);

    switch(index) {
        case 0: // 今日
            startDate = currentDate;
            endDate = currentDate;
            break;
        case 1: // 昨日
            startDate = currentDate.addDays(-1);
            endDate = currentDate.addDays(-1);
            break;
        case 2: // 本周
            startDate = currentDate.addDays(-(currentDate.dayOfWeek() - 1));
            endDate = currentDate;
            break;
        case 3: // 上周
            startDate = currentDate.addDays(-(currentDate.dayOfWeek() + 6));
            endDate = currentDate.addDays(-(currentDate.dayOfWeek()));
            break;
        case 4: // 本月
            startDate = QDate(currentDate.year(), currentDate.month(), 1);
            endDate = currentDate;
            break;
        case 5: // 上月
            if (currentDate.month() == 1) {
                startDate = QDate(currentDate.year() - 1, 12, 1);
                endDate = QDate(currentDate.year() - 1, 12, 31);
            } else {
                startDate = QDate(currentDate.year(), currentDate.month() - 1, 1);
                endDate = QDate(currentDate.year(), currentDate.month(), 1).addDays(-1);
            }
            break;
        case 6: // 自定义
            // 使用当前设置的日期
            startDate = startDateEdit->date();
            endDate = endDateEdit->date();
            break;
    }

    // 如果不是自定义，则更新日期选择器的值
    if (index != 6) {
        startDateEdit->setDate(startDate);
        endDateEdit->setDate(endDate);
    }

    // 更新图表和数据
    updateRevenueStats(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateRevenueChart(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateTransactionTable(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
}

void AdminWindow::updateBusinessFilter() {
    // 获取当前的日期范围
    QDate startDate = startDateEdit->date();
    QDate endDate = endDateEdit->date();

    // 更新图表和数据
    updateRevenueStats(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateRevenueChart(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateTransactionTable(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
}

void AdminWindow::customRevenueQuery() {
    QDate startDate = startDateEdit->date();
    QDate endDate = endDateEdit->date();

    // 检查日期范围是否有效
    if (startDate > endDate) {
        QMessageBox::warning(this, "日期错误", "开始日期不能晚于结束日期");
        return;
    }

    // 更新图表和数据
    updateRevenueStats(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateRevenueChart(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
    updateTransactionTable(startDate.toString("yyyy-MM-dd"), endDate.toString("yyyy-MM-dd"));
}

void AdminWindow::updateRevenueStats(const QString &startDate, const QString &endDate) {
    QSqlQuery query;
    query.prepare("SELECT SUM(o.total_price) as total_revenue, COUNT(o.order_id) as order_count FROM order_c o WHERE DATE(o.time_start) BETWEEN :start_date AND :end_date");
    query.bindValue(":start_date", startDate);
    query.bindValue(":end_date", endDate);
    if (!query.exec()) {
        qDebug() << "Error executing query:" << query.lastError();
    }
    if (query.next()) {
        double totalRevenue = query.value(0).toDouble();
        int orderCount = query.value(1).toInt();
        // 更新UI显示
        totalRevenueLabel->setText(QString("¥%1").arg(totalRevenue, 0, 'f', 2));
        orderCountLabel->setText(QString("%1").arg(orderCount));

        // 计算平均订单金额
        double avgOrderAmount = (orderCount > 0) ? (totalRevenue / orderCount) : 0;
        avgOrderLabel->setText(QString("¥%1").arg(avgOrderAmount, 0, 'f', 2));
    }
}

void AdminWindow::updateRevenueChart(const QString &startDate, const QString &endDate) {
    QSqlQuery query;
    query.prepare("SELECT DATE(o.time_start) AS day, SUM(o.total_price) as daily_revenue FROM order_c o WHERE DATE(o.time_start) BETWEEN :start_date AND :end_date GROUP BY DATE(o.time_start) ORDER BY day");
    query.bindValue(":start_date", startDate);
    query.bindValue(":end_date", endDate);
    if (!query.exec()) {
        qDebug() << "Error executing query:" << query.lastError();
    }

    // 创建线性图表
    QLineSeries *series = new QLineSeries();
    series->setName("日营收额");

    QStringList categories;
    QList<QPointF> points;

    // 添加数据点
    int index = 0;
    while (query.next()) {
        QString day = query.value(0).toString();
        double revenue = query.value(1).toDouble();

        series->append(index, revenue);
        categories << day;
        points << QPointF(index, revenue);
        index++;
    }

    // 创建图表
    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle("营收趋势");
    chart->setAnimationOptions(QChart::SeriesAnimations);

    // 添加X轴
    QBarCategoryAxis *axisX = new QBarCategoryAxis();
    axisX->append(categories);
    chart->addAxis(axisX, Qt::AlignBottom);
    series->attachAxis(axisX);

    // 添加Y轴
    QValueAxis *axisY = new QValueAxis();
    chart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);

    // 设置图表外观
    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);

    // 设置值标签
    series->setPointLabelsVisible(true);
    series->setPointLabelsFormat("@yPoint");

    // 更新图表视图
    revenueChartView->setChart(chart);
}

void AdminWindow::updateTransactionTable(const QString &startDate, const QString &endDate) {
    QSqlQuery query;
    query.prepare("SELECT o.order_id, o.business_id, o.total_price, o.time_start, o.quantity, o.user_id, o.address, CASE WHEN o.time_end IS NULL THEN '进行中' ELSE '已完成' END as status FROM order_c o WHERE DATE(o.time_start) BETWEEN :start_date AND :end_date ORDER BY o.time_start DESC");
    query.bindValue(":start_date", startDate);
    query.bindValue(":end_date", endDate);
    if (!query.exec()) {
        qDebug() << "Error executing query:" << query.lastError();
    }
    // 清空表格
    transactionTable->setRowCount(0);
    // 处理查询结果并填充表格
    while (query.next()) {
        int row = transactionTable->rowCount();
        transactionTable->insertRow(row);
        transactionTable->setItem(row, 0, new QTableWidgetItem(query.value("order_id").toString()));
        transactionTable->setItem(row, 1, new QTableWidgetItem(query.value("business_id").toString()));
        transactionTable->setItem(row, 2, new QTableWidgetItem(query.value("total_price").toString()));
        transactionTable->setItem(row, 3, new QTableWidgetItem(query.value("time_start").toString()));
        transactionTable->setItem(row, 4, new QTableWidgetItem(query.value("quantity").toString()));
        transactionTable->setItem(row, 5, new QTableWidgetItem(query.value("user_id").toString()));
        transactionTable->setItem(row, 6, new QTableWidgetItem(query.value("address").toString()));
        transactionTable->setItem(row, 7, new QTableWidgetItem(query.value("status").toString()));
    }
}

// 修改：刷新按钮点击事件
void AdminWindow::refreshRevenue() {
    // 使用当前设置的日期范围刷新数据
    customRevenueQuery();
}

// 申请审批
void AdminWindow::initApplicationReview() {
    applicationModel = new QSqlTableModel(this, db);
    applicationModel->setTable("review");
    applicationModel->setFilter("review_status = 0"); // 只显示待审核的申请
    applicationModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    applicationModel->select();

    // 设置表头
    applicationModel->setHeaderData(0, Qt::Horizontal, "申请ID");
    applicationModel->setHeaderData(1, Qt::Horizontal, "用户ID");
    applicationModel->setHeaderData(2, Qt::Horizontal, "审核状态");
    applicationModel->setHeaderData(3, Qt::Horizontal, "身份类型");
    applicationModel->setHeaderData(4, Qt::Horizontal, "名称");
    applicationModel->setHeaderData(5, Qt::Horizontal, "电话ID");
    applicationModel->setHeaderData(6, Qt::Horizontal, "地址ID");
    applicationModel->setHeaderData(7, Qt::Horizontal, "商户描述");
    applicationModel->setHeaderData(8, Qt::Horizontal, "电话");
    ui->applicationTableView->setModel(applicationModel);
    ui->applicationTableView->setItemDelegate(new ApplicationDelegate(this));
    ui->applicationTableView->resizeColumnsToContents();

    // 连接选择变更事件，显示申请详情
    connect(ui->applicationTableView->selectionModel(), &QItemSelectionModel::selectionChanged, [this]() {
        QModelIndex index = ui->applicationTableView->currentIndex();
        if (!index.isValid()) {
            ui->applicationDetailLabel->setText("选择一个申请查看详情");
            return;
        }

        int row = index.row();
        int reviewId = applicationModel->data(applicationModel->index(row, 0)).toInt();
        int userId = applicationModel->data(applicationModel->index(row, 1)).toInt();
        int identityObject = applicationModel->data(applicationModel->index(row, 3)).toInt();
        QString nameObject = applicationModel->data(applicationModel->index(row, 4)).toString();
        QString phoneId = applicationModel->data(applicationModel->index(row, 5)).toString();
        QString addressId = applicationModel->data(applicationModel->index(row, 6)).toString();
        QString busComment = applicationModel->data(applicationModel->index(row, 7)).toString();
        QString phone = applicationModel->data(applicationModel->index(row, 8)).toString();

        QString identityStr = (identityObject == 2) ? "商户" : "骑手";

        QString detailText = QString("申请ID: %1\n用户ID: %2\n申请类型: %3\n名称: %4\n电话ID: %5\n电话: %6")
                             .arg(reviewId).arg(userId).arg(identityStr).arg(nameObject).arg(phoneId).arg(phone);

        if (!addressId.isEmpty())
            detailText += QString("\n地址ID: %1").arg(addressId);

        if (!busComment.isEmpty())
            detailText += QString("\n商户描述: %1").arg(busComment);

        ui->applicationDetailLabel->setText(detailText);
    });
}

// 同意申请
void AdminWindow::approveApplication() {
    QModelIndex index = ui->applicationTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要审批的申请");
        return;
    }

    int row = index.row();
    int reviewId = applicationModel->data(applicationModel->index(row, 0)).toInt();
    int userId = applicationModel->data(applicationModel->index(row, 1)).toInt();
    int identityObject = applicationModel->data(applicationModel->index(row, 3)).toInt();
    QString nameObject = applicationModel->data(applicationModel->index(row, 4)).toString();
    QString phoneId = applicationModel->data(applicationModel->index(row, 5)).toString();
    QString addressId = applicationModel->data(applicationModel->index(row, 6)).toString();
    QString busComment = applicationModel->data(applicationModel->index(row, 7)).toString();
    QString phone = applicationModel->data(applicationModel->index(row, 8)).toString();

    // 调试信息
    qDebug() << "申请ID:" << reviewId;
    qDebug() << "用户ID:" << userId;
    qDebug() << "身份类型:" << identityObject;
    qDebug() << "名称:" << nameObject;
    qDebug() << "电话ID:" << phoneId;
    qDebug() << "地址ID:" << addressId;
    qDebug() << "商户描述:" << busComment;
    qDebug() << "电话:" << phone;

    // 确认操作
    QString identityStr = (identityObject == 2) ? "商户" : "骑手";
    QString confirmMsg = QString("确定要同意用户ID %1 的%2申请吗？\n同意后将删除该用户的普通用户信息。").arg(userId).arg(identityStr);

    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认操作", confirmMsg,
                                                             QMessageBox::Yes | QMessageBox::No);
    if (reply != QMessageBox::Yes) {
        return;
    }

    // 开始事务
    db.transaction();

    bool success = true;
    QSqlQuery query(db);

    // 验证必要的字段
    bool phoneIdOk = true;
    int phoneIdInt = phoneId.toInt(&phoneIdOk);
    if (!phoneIdOk || phoneIdInt <= 0) {
        QMessageBox::critical(this, "错误", "电话ID无效，必须是有效的整数");
        db.rollback();
        return;
    }

    if (identityObject == 2 && addressId.isEmpty()) { // 商户需要地址ID
        QMessageBox::critical(this, "错误", "商户申请需要有效的地址ID");
        db.rollback();
        return;
    }

    // 更新review表中的状态
    QString updateSql = QString("UPDATE review SET review_status = 1 WHERE review_id = %1").arg(reviewId);
    qDebug() << "执行SQL:" << updateSql;

    if (!query.exec(updateSql)) {
        success = false;
        qDebug() << "更新review表失败:" << query.lastError().text();
        qDebug() << "SQL:" << query.lastQuery();
    } else {
        qDebug() << "更新review表成功";
    }

    // 更新phone表中的identity字段和phone字段
    if (success) {
        // review表中的phone字段存储的是手机号
        QString newPhone = phone; // 这是申请中提交的新手机号

        // 更新phone表中的identity字段和phone字段
        QString updatePhoneSql = QString("UPDATE phone SET identity = %1, phone = '%2' WHERE phone_id = %3")
                                .arg(identityObject)
                                .arg(newPhone)
                                .arg(phoneIdInt);

        qDebug() << "执行SQL:" << updatePhoneSql;
        if (!query.exec(updatePhoneSql)) {
            success = false;
            qDebug() << "更新phone表失败:" << query.lastError().text();
        } else {
            qDebug() << "更新phone表成功，手机号更新为:" << newPhone;
        }
    }

    if (success) {
        if (identityObject == 2) { // 商户申请
            // 插入商户表
            qDebug() << "准备插入商户表，参数：" << nameObject << phoneIdInt << addressId;

            // 使用直接嵌入参数的方式构建SQL语句
            QString sql = QString("INSERT INTO business (business_name, phone_id, address_id, delivery, img, status) "
                                 "VALUES ('%1', %2, '%3', %4, '%5', %6)")
                          .arg(nameObject)
                          .arg(phoneIdInt)
                          .arg(addressId)
                          .arg(2.0)
                          .arg("")
                          .arg(1);

            qDebug() << "执行SQL:" << sql;
            if (!query.exec(sql)) {
                success = false;
                qDebug() << "插入商户表失败:" << query.lastError().text();
                qDebug() << "SQL:" << query.lastQuery();
                qDebug() << "参数:" << nameObject << phoneIdInt << addressId;
            } else {
                qDebug() << "插入商户表成功";
            }
        } else if (identityObject == 3) { // 骑手申请
            // 插入骑手表
            qDebug() << "准备插入骑手表，参数：" << nameObject << phoneIdInt;

            // 使用直接嵌入参数的方式构建SQL语句
            QString sql = QString("INSERT INTO rider (rider_name, phone_id, Income, status) "
                                 "VALUES ('%1', %2, %3, %4)")
                          .arg(nameObject)
                          .arg(phoneIdInt)
                          .arg(0)
                          .arg(1);

            qDebug() << "执行SQL:" << sql;
            if (!query.exec(sql)) {
                success = false;
                qDebug() << "插入骑手表失败:" << query.lastError().text();
                qDebug() << "SQL:" << query.lastQuery();
                qDebug() << "参数:" << nameObject << phoneIdInt;
            } else {
                qDebug() << "插入骑手表成功";
            }
        }
    }

    if (success) {
        // 删除用户表中的记录
        qDebug() << "准备删除用户表记录，用户ID：" << userId;

        // 使用直接嵌入参数的方式构建SQL语句
        QString sql = QString("DELETE FROM user WHERE user_id = %1").arg(userId);

        qDebug() << "执行SQL:" << sql;
        if (!query.exec(sql)) {
            success = false;
            qDebug() << "删除用户表记录失败:" << query.lastError().text();
            qDebug() << "SQL:" << query.lastQuery();
        } else {
            qDebug() << "删除用户表记录成功";
        }
    }

    // 提交或回滚事务
    if (success) {
        db.commit();
        QMessageBox::information(this, "成功", "申请已审核通过");
        applicationModel->select(); // 刷新表格
        ui->applicationDetailLabel->setText("选择一个申请查看详情");
    } else {
        db.rollback();
        QMessageBox::critical(this, "错误", "审核操作失败: " + query.lastError().text());
    }
}

// 拒绝申请
void AdminWindow::rejectApplication() {
    QModelIndex index = ui->applicationTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要拒绝的申请");
        return;
    }

    int row = index.row();
    int reviewId = applicationModel->data(applicationModel->index(row, 0)).toInt();
    int userId = applicationModel->data(applicationModel->index(row, 1)).toInt();
    int identityObject = applicationModel->data(applicationModel->index(row, 3)).toInt();

    // 确认操作
    QString identityStr = (identityObject == 2) ? "商户" : "骑手";
    QString confirmMsg = QString("确定要拒绝用户ID %1 的%2申请吗？").arg(userId).arg(identityStr);

    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认操作", confirmMsg,
                                                              QMessageBox::Yes | QMessageBox::No);
    if (reply != QMessageBox::Yes) {
        return;
    }

    QSqlQuery query(db);
    query.prepare("UPDATE review SET review_status = 2 WHERE review_id = ?");
    query.addBindValue(reviewId);

    if (query.exec()) {
        applicationModel->select();
        QMessageBox::information(this, "成功", "申请已拒绝");
        ui->applicationDetailLabel->setText("选择一个申请查看详情");
    } else {
        QMessageBox::critical(this, "错误", "拒绝操作失败: " + query.lastError().text());
    }
}

#ifdef ENABLE_COMMENT_MANAGEMENT
// 评论管理初始化
void AdminWindow::initCommentManagement() {
    commentModel = new QSqlTableModel(this, db);
    commentModel->setTable("comment");  // 评论表名为 comment
    commentModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    commentModel->select();

    // 设置表头
    commentModel->setHeaderData(0, Qt::Horizontal, "评论ID");
    commentModel->setHeaderData(1, Qt::Horizontal, "订单ID");
    commentModel->setHeaderData(2, Qt::Horizontal, "用户ID");
    commentModel->setHeaderData(3, Qt::Horizontal, "评论内容");
    commentModel->setHeaderData(4, Qt::Horizontal, "评论时间");
    commentModel->setHeaderData(5, Qt::Horizontal, "评分");

    // 设置模型到表格视图
    ui->commentTableView->setModel(commentModel);
    ui->commentTableView->resizeColumnsToContents();
}

// 添加评论
void AdminWindow::addComment() {
    int row = commentModel->rowCount();
    commentModel->insertRow(row);
    QMessageBox::information(this, "提示", "请在表格中编辑新评论信息，完成后点击保存按钮");
}

// 删除评论
void AdminWindow::deleteComment() {
    QModelIndex index = ui->commentTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的评论");
        return;
    }

    int row = index.row();
    commentModel->removeRow(row);
    QMessageBox::information(this, "提示", "评论已标记为删除，点击保存按钮确认删除");
}

// 保存评论更改
void AdminWindow::saveCommentChanges() {
    if (commentModel->submitAll()) {
        QMessageBox::information(this, "成功", "评论数据已保存");
    } else {
        QMessageBox::critical(this, "错误", "保存评论数据失败: " + commentModel->lastError().text());
        commentModel->revertAll();
    }
}
#endif
